package com.huahua.api.service.impl;

import cn.hutool.core.util.StrUtil;
import com.huahua.api.entity.dto.DmxApiContent;
import com.huahua.api.entity.dto.DmxApiMessageV2;
import com.huahua.api.entity.dto.DmxApiRequestV2;
import com.huahua.api.entity.param.TranslationParam;
import com.huahua.api.service.DmxApiService;
import com.huahua.api.service.TranslationService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class TranslationServiceImpl implements TranslationService {

    private final DmxApiService dmxApiService;

    /**
     * 优化后的系统提示词：
     * - 支持自动识别源语言（当 [source language] = auto）
     * - 强化术语、缩略语、网络用语、口语化风格与“仅输出译文”规则
     * - 保留并显式加入 system hint: please always use the thinking mode
     */
    private static final String SYSTEM_PROMPT = """
            You are a professional linguist who graduated from a top-tier university.
            System hint: please always use the thinking mode.
            
            Your mission is to accurately translate the source text from the specified source language into the specified target language.
            
            Guidelines:
            - Accuracy & Fluency: Faithfully convey meaning and structure using natural, fluent language. Avoid stiff, mechanical, or overly wordy phrasing.
            - Context & Terminology: Understand context deeply and use specialized terminology appropriately.
            - Abbreviations: Accurately capture abbreviations without over-interpreting or misrepresenting them.
            - Niche/Hard Terms: For niche, technical, or hard-to-translate terms, keep the original word untranslated.
            - Internet Slang: Recognize and translate internet slang naturally, making the text engaging when suitable.
            - Conversational Style: Ensure the translation matches the target language’s common expressions and natural conversational style.
            - Language Detection: If [source language] is "auto", detect the source language before translating.
            
            Output Rule:
            - Only output the translated text. No explanations, no extra commentary.
            """;

    @Override
    public Flux<String> translateStream(TranslationParam param) {
        // 基本校验
        if (StrUtil.isEmptyIfStr(param.getContent())) {
            return Flux.error(new IllegalArgumentException("请填写文本"));
        }
        if (StrUtil.isEmptyIfStr(param.getTargetLanguage())) {
            return Flux.error(new IllegalArgumentException("请选择目标语言类型"));
        }
        if (StrUtil.isEmptyIfStr(param.getSourceLanguage())) {
            return Flux.error(new IllegalArgumentException("请选择源语言类型"));
        }

        final String userPrompt = buildUserPrompt(param.getSourceLanguage(), param.getTargetLanguage(), param.getContent());

        List<DmxApiMessageV2> messages = new ArrayList<>();

        // system 指令
        messages.add(DmxApiMessageV2.builder()
                .role("system")
                .content(List.of(DmxApiContent.builder()
                        .type("text")
                        .text(SYSTEM_PROMPT)
                        .build()))
                .build());

        // user 指令（结构化输入）
        messages.add(DmxApiMessageV2.builder()
                .role("user")
                .content(List.of(DmxApiContent.builder()
                        .type("text")
                        .text(userPrompt)
                        .build()))
                .build());

        DmxApiRequestV2 request = DmxApiRequestV2.builder()
                .model("DMXAPI-HuoShan-DeepSeek-V3")
                .stream(true)
                .messages(messages)
                .build();

        return dmxApiService.chatCompletions(request);
    }

    /**
     * 构建结构化用户提示：
     * [source language: ...]
     * [target language: ...]
     * [text to translate: ...]
     */
    private static String buildUserPrompt(String sourceLang, String targetLang, String content) {
        return """
                [source language: %s]
                [target language: %s]
                [text to translate: %s]
                """.formatted(sourceLang, targetLang, content);
    }
}
